package com.example.data.factory.common.Interector;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.data.factory.common.result.R;
import com.example.data.factory.common.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class LoginIntorector implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, String> map = new HashMap<> ();

        // 获取 Token
        String token = request.getHeader ( "Authorization" );
        if (token == null || token.isEmpty ()) {
            map.put ( "msg", "缺少 Token" );
            writeErrorResponse ( response, map );
            return false;
        }

        // 去掉 Bearer 前缀
        if (token.startsWith ( "Bearer " )) {
            token = token.substring ( 7 );
        }

        try {
            // 校验 Token
            DecodedJWT verifyToken = jwtConfig.verifyToken ( token );
            return true; // 校验成功，放行请求
        } catch (Exception e) {
            e.printStackTrace (); // 打印异常堆栈
            map.put ( "msg", "Token 验证失败: " + e.getMessage () );
            map.put ( "errorType", e.getMessage ().contains ( "expired" ) ? "TOKEN_EXPIRED" : "INVALID_TOKEN" );
            writeErrorResponse ( response, map );
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后执行的逻辑（可选）
    }

    /**
     * 写入错误响应
     */
    private void writeErrorResponse(HttpServletResponse response, HashMap<String, String> map) throws Exception {
        response.setContentType ( "application/json;charset=UTF-8" );
        response.getWriter ().write ( new ObjectMapper ().writeValueAsString ( R.Failed ( map.get ( "msg" ) ) ) );
    }
}